package com.cfk.shopmail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cfk.shopmail.product.service.CategoryBrandRelationService;
import com.cfk.shopmail.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cfk.common.utils.PageUtils;
import com.cfk.common.utils.Query;

import com.cfk.shopmail.product.dao.CategoryDao;
import com.cfk.shopmail.product.entity.CategoryEntity;
import com.cfk.shopmail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子结构类型

        //2.1) 找到所有的一级分类
        List<CategoryEntity> levelOneMenu = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> { //匹配子集菜单
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList()); //收集为集合
        return levelOneMenu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO //1.检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //查询子菜单的目录路径
    @Override
    public Long[] findCategoryPathById(Long catelogId) {
        List<Long> path = new ArrayList<>();
        //设置一个方法直接查找路径集合
        List<Long> currentPath = findPath(path, catelogId);
        //利用工具类反转集合
        Collections.reverse(currentPath);
        //把集合转为数组
        return path.toArray(new Long[0]);
    }

    //递归查询路径 注意此时保存的路径与实际路径相反
    private List<Long> findPath(List<Long> path, Long catelogId) {
        //首先保存当前路径
        path.add(catelogId);
        //通过id查找此时的类
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findPath(path, categoryEntity.getParentCid());
        }
        return path;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }


    //修改分类的同时修改其关联表
    // @Caching(evict = {
    //         @CacheEvict(value = "category", key = "'getLevelOneCategorys'"),
    //         @CacheEvict(value = "category", key = "'getCatalogJson'")
    // })
    @CacheEvict(value = "category", allEntries = true) //删除这个分区下的所有数据 失效模式
    // @CachePut//双写模式
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

        //TODO
    }

    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    //================================web===============================================
    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevelOneCategorys() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;

    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");
        /**
         * 1.将所有的数据先查询出来
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> levelOneCategorys = getParent_cid(selectList, 0L);

        //2.封装数据
        Map<String, List<Catelog2Vo>> map = levelOneCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> level2Catelog = getParent_cid(selectList, v.getCatId());

            List<Catelog2Vo> catelog2Vos = null;
            //2.封装上面的结果返回前端
            if (level2Catelog != null) {
                catelog2Vos = level2Catelog.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找当前二级分类的三级分类进行封装
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2.封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return map;

    }

    /**
     * 1.空结果缓存:解决缓存穿透
     * 2.设置过期时间(加随机值):解决缓存雪崩
     * 3.加锁:解决缓存击穿
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //1.加入缓存逻辑
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            System.out.println("未击中，将查询数据库");
            //2.缓存中没有数据
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();
            return catalogJsonFromDb;
        }
        System.out.println("击中，查询数据库");

        //转为我们指定的对象
        Map<String, List<Catelog2Vo>> result = JSONObject.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    //TODO 本地锁，对于单服务器的部署来说是没有问题的，但是当把商品服务部署到多个服务的时候就会出现问题了，因为这样对应每个商品服务对应一个服务
    // 器有多少个就创建多少个锁
    //从数据查询并封装分类数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this) {
            return getDataFromDb();
        }

    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        //1.占用分布式的锁，去redis占坑
        String uuid = UUID.randomUUID().toString();//每一个锁的标识符
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            //加锁成功
            //因为有可能服务突然崩溃，异常，或者停电导致程序未能执行完，无法释放锁，所以要设置一个过期时间
            //但是由于这样设置过期时间也有可能未执行就直接停电了，所以获取锁以及设置过期时间必须是一个原子操作
            Map<String, List<Catelog2Vo>> dataFromDb = null;
            try {
                // redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
                dataFromDb = getDataFromDb();
            } finally {
                // redisTemplate.delete("lock");//删除锁

                //获取值对比+对比成功删除=原子操作 luo脚本解锁
                // String lockValue = redisTemplate.opsForValue().get("lock");
                // if (uuid.equals(lockValue)) {
                //     //删除自己的锁
                //     redisTemplate.delete("lock");
                // }
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }

            return dataFromDb;
        } else {
            //加锁失败..重试
            System.out.println("获取分布式锁失败");
            return getCatalogJsonFromDbWithRedisLock();//自旋的方式

        }

    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        //1.锁的名字，锁的粒度，越细越快
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }

        return dataFromDb;


    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSONObject.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库");
        /**
         * 1.将所有的数据先查询出来
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> levelOneCategorys = getParent_cid(selectList, 0L);

        //2.封装数据
        Map<String, List<Catelog2Vo>> map = levelOneCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> level2Catelog = getParent_cid(selectList, v.getCatId());

            List<Catelog2Vo> catelog2Vos = null;
            //2.封装上面的结果返回前端
            if (level2Catelog != null) {
                catelog2Vos = level2Catelog.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找当前二级分类的三级分类进行封装
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2.封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //3.查到的数据放入缓存,将对象转为json放在缓存中
        String s = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return map;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return collect;

    }

}